package com.study.manage.mvc.org.orgdetails;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.OrgShopRepository;
import com.study.manage.dal.UserRepository;
import com.study.manage.domain.OrgShop;
import com.study.manage.domain.User;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.domain.enumm.OrgShopType;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.SessionUser;
import com.study.manage.mvc.common.BaseController;

@Controller
@RequestMapping("org/acc")
@Scope("request")
public class OrgDetailsController extends BaseController {

	@Autowired
    private UserRepository userRepository;
    @Autowired
    private OrgShopRepository orgShopRepository;

    @RequestMapping(path = "orgdetails", method = RequestMethod.GET)
    public String findOrgShop(ModelMap model) {
    	
    	SessionUser su = (SessionUser) session.getAttribute("user");
        User user = userRepository.findOne(su.getId());
        Map<String, Object> map = new HashMap<>();
        List<OrgShop> orgShops = orgShopRepository.findByUserIdAndState(user.id, LiveDieState.LIVE);
        for (OrgShop os : orgShops) {
            map.put(os.type.toString(), os.url);
        }
        map.put("isBrandOrg", user.isBrandOrg);
        model.put("data", map);
        return "org/acc/orgdetails";
    }

    @ResponseBody
    @RequestMapping(path = "saveOrgShop", method = RequestMethod.POST)
    public AjaxResponse saveOrgShop(OrgDetailsForm form , ModelMap model) throws Exception {
    	
    	AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = (SessionUser) session.getAttribute("user");
        User user = userRepository.findById(su.getId());
        user.isBrandOrg = form.getIsBrandOrg();
        userRepository.save(user);
        
        updateOrgShop(su.getId(),OrgShopType.MT,form.getMt());
        updateOrgShop(su.getId(),OrgShopType.DZ,form.getDz());
        updateOrgShop(su.getId(),OrgShopType.GW,form.getGw());
        return ajax;
    }

	private void updateOrgShop(Long userId, OrgShopType type, String url) {
		
		OrgShop orgShop = orgShopRepository.findByUserIdAndTypeAndState(userId, type, LiveDieState.LIVE);
        if (orgShop != null) {
        	orgShop.url = url;
        } else {
        	orgShop = new OrgShop();
        	orgShop.type = type;
        	orgShop.userId = userId;
        	orgShop.url = url;
        }
        orgShopRepository.save(orgShop);
	}
}
